function checkForTorrentFile(e) {
    /*
     * checks every click and sees if it's a torrent file
     * if it is it initiates the download process otherwise nuttin
     */
    var target=e.target;
    target=target+"";
        if(/^http:\/\//.test(target) || /^file:\/\/\//.test(target)) {
//        if(/^file:\/\/\//.test(target)) {//for debuging purposes
            if (/torrent/.test(target)) {
                //it's a torrent file
                ret=getTorrentMetaFileAndSave(target);
                if (ret) 
                    return ret;
                else
                    return false;
            }
            else return false;
        }
}
function checkForAndFixPreferencesDirectories() {
    /*
     * If the bt preferences folder is not there then it needs to be created
     */
    file=getPrefDir();
    pref_path=file.path
    file.append('bt');
    if( !file.exists() || !file.isDirectory() ) {   // if it doesn't exist, create
        file.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0777);
    }
    file.append('torrentfiles');
    if( !file.exists() || !file.isDirectory() ) {   // if it doesn't exist, create
        file.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0777);
    }
}
function downloadFile(httpLoc,dest) {
/*
 * Saves the torrent file into the %profile%/preferences/bt/torrentfiles/ directory
 * This code used almost verbatim from
 * http://developer.mozilla.org/en/docs/nsIWebBrowserPersist#saveChannel.28.29
 */
	try {			
		//new obj_URI object
		var obj_URI = Components.classes["@mozilla.org/network/io-service;1"]
            .getService(Components.interfaces.nsIIOService).newURI(httpLoc, null, null);

		//new file object
		var obj_TargetFile = Components.classes["@mozilla.org/file/local;1"]
            .createInstance(Components.interfaces.nsILocalFile);
		//set file with path
		obj_TargetFile.initWithPath(dest.path);
		//if file doesn't exist, create
		if(!obj_TargetFile.exists()) {
            //empty file, readable by all writable by all
			obj_TargetFile.create(0x00,0666);
		}
		//new persitence object
		var obj_Persist = Components.classes["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"]
            .createInstance(Components.interfaces.nsIWebBrowserPersist);

		//save file to target
		obj_Persist.saveURI(obj_URI,null,null,null,null,obj_TargetFile);
	} catch (e) {
		alert(e);
	}
}

function getTorrentMetaFileAndSave(url) {
    /*
     * Save the meta file and get the destination directory from the user
     */
//  chop off the torrent file name
    name=url.split('/').pop()
    checkForAndFixPreferencesDirectories();
    torrents_dir=getTorrentFilesDir();
    save_dir=getSaveDirFromUser();
    //if the user hits cancel on the download dir
    //query then we need to not do anything
    save_dir=(save_dir) ? save_dir.path : false;
    if (!save_dir) return false;
    //downloadfile into %profile%/bt/torrentfiles
    dest=getTorrentFilesDir();
    dest.append(unescape(name))
    downloadFile(url,dest);
    /*BUILDING LINE*/
    return {'dl_dest':save_dir,'torrent_file':dest.path}
}


/*
 * The below code is used to interupt the downloading of a file by the download manager
 */
//var btContentListener = {
//    QueryInterface: function(aIID) {
//        if (aIID.equals(Components.interfaces.nsISupports) || aIID.equals(Components.interfaces.nsIURIContentListener)
//        || aIID.equals(Components.interfaces.nsISupportsWeakReference))
//            return this;
//        throw Components.results.NS_NOINTERFACE;
//    },
//
//    canHandleContent: function ( /*char* */ contentType , /*function*/ isContentPreferred , 
//        /*out char* */ desiredContentType ) {
//        dump("contentType="+contentType+"\n\n");
//        if (contentType == "application/x-bittorrent"){
//            return true;
//        }
//        else return false;
//    },
//
//    doContent: function ( /*char* */ contentType , /*function*/ isContentPreferred , 
//        /*nsIRequest*/ request , /*out nsIStreamListener*/ contentHandler ) {
//        /* blocks the download manager */
//        dump("contentType="+contentType+"\n\n");
//        return true;
//    },
//
//    isPreferred: function ( /*char* */ contentType , /*out char* */ desiredContentType ) {
//        dump("contentType="+contentType+"\n\n");
//        if (contentType == "application/x-bittorrent")
//            return true;
//        else
//            return false;
//    },
////    onStartURIOpen: function ( /*nsURI*/
//
//}
///* registers the above listener */
//Components.classes["@mozilla.org/uriloader;1"].getService(Components.interfaces.nsIURILoader).registerContentListener(btContentListener);
